/**
 * Alibaba.com.cn Inc.
 * Copyright (c) 2004-2021 All Rights Reserved.
 */
package com.yongbao.controller;

import com.yongbao.common.Constants;
import com.yongbao.common.enums.ErrorCode;
import com.yongbao.common.service.RedisService;
import com.yongbao.common.utils.AssertUtil;
import com.yongbao.mapper.UserMapper;
import com.yongbao.model.vo.UserVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhanghong
 * @version BaseController.java, v 0.1 2022/3/21 09:56 下午 BaseController Exp $$
 */
@Component
public class BaseController {
    @Autowired
    private RedisService redisService;
    @Autowired
    private UserMapper userMapper;

    /**
     * 小程序用户端-登录校验
     *
     * @param request
     */
    public <T> T validUserLoginAndGet(HttpServletRequest request, Class<T> clazz) {
        String token = request.getHeader(Constants.TOKEN);
        AssertUtil.assertNotNull(token, ErrorCode.NOT_LOGIN);
        T value = redisService.getKey(String.format(Constants.LOGIN_USER_RDB_PREFIX, token), clazz);
        AssertUtil.assertUserNotNull(value, ErrorCode.NOT_LOGIN);
        UserVO xcxUserVO = (UserVO) value;
        userMapper.selectDOById(xcxUserVO.getId());

        //校验是否已经被禁用
        //AssertUtil.assertTrue(xcxUser.getStatus() == BooleanEnum.TRUE.getCode(), ErrorCode.ERR_NO_PERMISSION, "账号禁用中，请联系平台");
        return (T) xcxUserVO;
    }

    /**
     * 小程序用户端-获取用户信息
     *
     * @param request
     */
    public <T> T getLoginUser(HttpServletRequest request, Class<T> clazz) {
        String token = request.getHeader(Constants.TOKEN);
        if (StringUtils.isBlank(token)) {
            return null;
        }
        T value = redisService.getKey(String.format(Constants.LOGIN_USER_RDB_PREFIX, token), clazz);
        return value;
    }

    /**
     * 小程序用户端-退出登陆
     *
     * @param request
     * @return
     */
    public boolean logoutUser(HttpServletRequest request) {
        String token = request.getHeader(Constants.TOKEN);
        AssertUtil.assertNotNull(token, ErrorCode.NOT_LOGIN);
        String key = redisService.getKey(String.format(Constants.LOGIN_USER_RDB_PREFIX, token));
        if (StringUtils.isNotBlank(key)) {
            redisService.del(key);
        }
        return true;
    }

}
